//
//  YSOrdinaryOrderDetailCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/8/5.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  普通订单详情

#import "YSOrdinaryOrderDetailCtrl.h"
#import "YSOrdinaryOrderDetailHeaderView.h"
#import "YSOrderCell.h"
#import "YSMineDataTool.h"
#import "YSOrdinaryOrderDetailFooterView.h"
#import "YSOrderDetailBottomBar.h"
#import "YSAccountCenterCtrl.h"
#import "YSAccountOrderStatusCtrl.h"
#import "YSOrderDeliveryCtrl.h"
#import "YSProductDetailCtrl.h"
#import "YSOrderBusinessHeaderView.h"
#import "YSBusinessCtrl.h"
#import "YSOrderDetailRemarkFooterView.h"

@interface YSOrdinaryOrderDetailCtrl ()<UITableViewDataSource,UITableViewDelegate,YSOrderDetailBottomBarDelegate,YSAccountCenterDelegate,YSAccountOrderStatusDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) YSOrdinaryOrderDetailHeaderView *headerView;
@property (strong, nonatomic) YSOrdinaryOrderDetailFooterView *footerView;
@property (strong, nonatomic) NSMutableArray *itemArray;
@property (strong, nonatomic) YSOrder *order;
@property (strong, nonatomic) YSOrderDetailBottomBar *bottomBar;

@end

@implementation YSOrdinaryOrderDetailCtrl

-(instancetype)initWithOrder:(YSOrder *)order{
    self = [super init];
    if(self){
        self.order = order;
    }
    return self;
}

-(NSMutableArray *)itemArray{
    if(!_itemArray){
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"订单详情"];
    [self initViews];
    [self requestData];
}

-(void)requestData{
    [YSMineDataTool getOrderDetailWithOrderCode:self.order.orderCode success:^(YSOrderDetailRes *result) {
        if(result.isSucc){
            self.headerView = [YSOrdinaryOrderDetailHeaderView headerView];
            [self.tableView setTableHeaderView:self.headerView];
            [self.headerView setResult:result];
            [self.headerView setOrder:self.order];
            self.order.satisfyFreight = result.satisfyFreight;
            self.footerView = [[YSOrdinaryOrderDetailFooterView alloc]initWithFooterView:self.order voucherAmount:result.voucherAmount];
            [self.tableView setTableFooterView:self.footerView];
            [self.itemArray removeAllObjects];
            [self.itemArray addObjectsFromArray:result.supplierList];
            [self.tableView reloadData];
        }else{
            if(result.code == 1001 || result.code == 1002){
                [Utils clearExitInfo];
                [Utils showLoginCtrl:self];
            }
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
}

-(void)initViews{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH-NavWithStatusBarH) style:UITableViewStylePlain];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setBackgroundColor:PUBLIC_BG];
    [self.view addSubview:self.tableView];
    if(self.order.orderStatus == OrderOrdinaryChildNotPayType||self.order.orderStatus == OrderOrdinaryChildNotReceiveType){
        
        self.bottomBar = [YSOrderDetailBottomBar bottomBar];
        [self.bottomBar setWidth:SCREENW];
        [self.bottomBar setDelegate:self];
        if(self.order.orderStatus == OrderOrdinaryChildNotPayType){
            [self.bottomBar.leftBtn setTitle:@"取消" forState:UIControlStateNormal];
            [self.bottomBar.rightBtn setTitle:@"立即支付" forState:UIControlStateNormal];
        }
        if(self.order.orderStatus == OrderOrdinaryChildNotReceiveType){
            [self.bottomBar.leftBtn setTitle:@"查看物流" forState:UIControlStateNormal];
            [self.bottomBar.rightBtn setTitle:@"确认收货" forState:UIControlStateNormal];
        }
        [self.bottomBar setY:SCREENH-self.bottomBar.height-NavWithStatusBarH];
        [self.view addSubview:self.bottomBar];
        self.tableView.height = SCREENH-NavWithStatusBarH-self.bottomBar.height;
    }
    
}

-(void)bottomBtnClick:(NSInteger)tag{
    if(self.order.orderStatus == OrderOrdinaryChildNotPayType){
        if(tag == 0){//取消
            [self cancleOrder:self.order.orderCode];
        }else{//立即支付
            YSAccountCenterCtrl *ctrl =  [[YSAccountCenterCtrl alloc]initWithOrdreCode:self.order.orderCode  selectProdIds:nil targetType:accountCenterFinishOrderDetailType productType:ordinaryProductType];
            [ctrl setDelegate:self];
            [self.navigationController pushViewController:ctrl animated:YES];
        }
    }
    
    if(self.order.orderStatus == OrderOrdinaryChildNotReceiveType){
        if(tag == 0){//查看物流
            [self.navigationController pushViewController:[[YSOrderDeliveryCtrl alloc] initWithOrderCode:self.order.orderCode] animated:YES];
        }else{//确认收货
            [self enterOrder:self.order.orderCode];
        }
    }
}

-(void)accountCenterFinish:(int)type status:(NSString *)status{
    if(type == accountCenterFinishOrderDetailType){
        [self toOrderStatusPage:status];
    }
}

/**
 *  结算中心页面关闭,回调跳转至支付状态页面
 *
 *  @param resultCode 状态码
 */
-(void)toOrderStatusPage:(NSString *)resultCode
{
    YSAccountOrderStatusCtrl *ctr = [YSAccountOrderStatusCtrl initWithResultCode:resultCode targetType:orderStatusFinishOrderDetailType];
    ctr.delegate = self;
    //进入状态页面
    [self.navigationController pushViewController:ctr  animated:YES];
}

/**
 *  订单状态页面关闭,回调跳转至订单列表页
 *
 *  @param type
 */
-(void)orderStatusFinish:(int)type
{
    if(orderStatusFinishOrderDetailType == type){
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)enterOrder:(NSString *)orderCode{
    [YSMineDataTool enterWithOrderCode:orderCode success:^(BaseResponse *result) {
        if(result.isSucc){
            [self.navigationController popViewControllerAnimated:YES];
        }else{
           ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
}


/**
 *  取消订单
 */
-(void)cancleOrder:(NSString *)orderCode{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"取消订单" message:@"确定要取消吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [DefaultsHelper setObject:orderCode forKey:kOrderCode];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSString *orderCode = [DefaultsHelper stringForKey:kOrderCode];
        [YSMineDataTool cancleOrderWithOrderCode:orderCode success:^(BaseResponse *result) {
            if(result.isSucc){
                 [DefaultsHelper setObject:nil forKey:kOrderCode];
                 [[NSNotificationCenter defaultCenter]postNotificationName:kSubviewsUpdateOrderStatus object:nil];
                 [self.navigationController popViewControllerAnimated:YES];
            }else{
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            ShowTips(kRequestFailure);
        }];
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return  self.itemArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.itemArray[section] prodList].count;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    YSOrderBusinessHeaderView *headerView = [YSOrderBusinessHeaderView headerView];
    UITapGestureRecognizer *tap =  [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openBusiness:)];
    [headerView addGestureRecognizer:tap];
    [headerView setWidth:SCREENW];
    [headerView setTag:section];
    [headerView setSupplier:_itemArray[section]];
    return headerView;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return YSOrderBusinessHeaderViewHeight;
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if(!ISBLANK([_itemArray[section] userRemark])){
        YSOrderDetailRemarkFooterView *footerView = [YSOrderDetailRemarkFooterView footerView];
        footerView.backLabel.text = [_itemArray[section] userRemark];
        return footerView;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(!ISBLANK([_itemArray[section] userRemark])){
        CGSize size = [[_itemArray[section] userRemark] sizeWithFont:SYS_FONT(13) constrainedToSize:CGSizeMake(SCREENW-YSPublicXInset*2, MAXFLOAT)];
        return YSPublicXInset*2+size.height;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YSOrderCell *cell =  [YSOrderCell cellWithTableView:tableView];
    cell.product = [self.itemArray[indexPath.section] prodList][indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return YSOrderCellHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSInteger prodId = [[self.itemArray[indexPath.section] prodList][indexPath.row]prodMainId];
    YSProductDetailCtrl *ctrl =  [[YSProductDetailCtrl alloc]initWithProdId:prodId];
    [self.navigationController pushViewController:ctrl animated:YES];
}

-(void)openBusiness:(UITapGestureRecognizer *)sender{
    YSSupplier *supplier =   _itemArray[sender.view.tag];
    NSInteger supplierId =   supplier.supplierId;
    YSBusinessCtrl *ctrl =  [[YSBusinessCtrl alloc]initWithSupplierId:supplierId];
    [self.navigationController pushViewController:ctrl animated:YES];
}

@end
